<script setup lang="ts">
import { ref } from 'vue'
import { jsPDF } from 'jspdf'
import imageCompression from 'browser-image-compression'

interface ImageFile {
  file: File
  preview: string
  name: string
}

const images = ref<ImageFile[]>([])
const isProcessing = ref(false)
const maxImages = 10
const maxFileSize = 5 // MB

const handleFileSelect = async (event: Event) => {
  const fileList = (event.target as HTMLInputElement).files
  if (!fileList) return

  const newFiles = Array.from(fileList).slice(0, maxImages - images.value.length)
  
  for (const file of newFiles) {
    if (!file.type.startsWith('image/')) {
      alert('请只上传图片文件')
      continue
    }

    // 压缩图片
    const options = {
      maxSizeMB: maxFileSize,
      maxWidthOrHeight: 2000,
      useWebWorker: true
    }

    try {
      const compressedFile = await imageCompression(file, options)
      const preview = await imageCompression.getDataUrlFromFile(compressedFile)
      
      images.value.push({
        file: compressedFile,
        preview,
        name: file.name
      })
    } catch (error) {
      console.error('Error processing image:', error)
      alert('处理图片时出错')
    }
  }
}

const removeImage = (index: number) => {
  images.value.splice(index, 1)
}

const moveImage = (index: number, direction: 'up' | 'down') => {
  if (direction === 'up' && index > 0) {
    [images.value[index], images.value[index - 1]] = [images.value[index - 1], images.value[index]]
  } else if (direction === 'down' && index < images.value.length - 1) {
    [images.value[index], images.value[index + 1]] = [images.value[index + 1], images.value[index]]
  }
}

const generatePDF = async () => {
  if (images.value.length === 0) {
    alert('请先添加图片')
    return
  }

  isProcessing.value = true
  const pdf = new jsPDF()
  
  try {
    for (let i = 0; i < images.value.length; i++) {
      if (i > 0) {
        pdf.addPage()
      }
      
      const img = images.value[i].preview
      const imgProps = pdf.getImageProperties(img)
      const pdfWidth = pdf.internal.pageSize.getWidth()
      const pdfHeight = pdf.internal.pageSize.getHeight()
      
      // 计算适合页面的图片尺寸
      const ratio = Math.min(
        pdfWidth / imgProps.width,
        pdfHeight / imgProps.height
      )
      const width = imgProps.width * ratio
      const height = imgProps.height * ratio
      
      // 居中显示
      const x = (pdfWidth - width) / 2
      const y = (pdfHeight - height) / 2
      
      pdf.addImage(img, 'JPEG', x, y, width, height)
    }
    
    pdf.save('converted-images.pdf')
  } catch (error) {
    console.error('Error generating PDF:', error)
    alert('生成PDF时出错')
  } finally {
    isProcessing.value = false
  }
}

const clearImages = () => {
  images.value = []
}
</script>

<template>
  <div class="max-w-4xl p-4 mx-auto">
    <div class="p-6 bg-white rounded-lg shadow dark:bg-gray-800">
      <div class="mb-6">
        <h2 class="mb-2 text-2xl font-bold">图片转PDF工具</h2>
        <p class="text-gray-600 dark:text-gray-400">
          将多张图片合并为一个PDF文件。支持拖拽排序，最多可添加{{ maxImages }}张图片。
        </p>
      </div>

      <div class="space-y-4">
        <!-- 上传按钮 -->
        <div class="flex justify-center">
          <label 
            class="px-6 py-3 text-white transition-colors bg-blue-500 rounded-lg cursor-pointer hover:bg-blue-600"
            :class="{ 'opacity-50 cursor-not-allowed': images.length >= maxImages }"
          >
            <input
              type="file"
              multiple
              accept="image/*"
              class="hidden"
              @change="handleFileSelect"
              :disabled="images.length >= maxImages"
            >
            <span class="flex items-center">
              <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
              </svg>
              选择图片
            </span>
          </label>
        </div>

        <!-- 图片预览区 -->
        <div v-if="images.length > 0" class="space-y-4">
          <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <div 
              v-for="(image, index) in images" 
              :key="index"
              class="relative p-2 bg-gray-100 rounded-lg group dark:bg-gray-700"
            >
              <img 
                :src="image.preview" 
                :alt="image.name"
                class="object-contain w-full h-48 rounded"
              >
              <div class="absolute inset-0 flex items-center justify-center transition-opacity bg-black bg-opacity-0 rounded-lg opacity-0 group-hover:bg-opacity-40 group-hover:opacity-100">
                <div class="flex space-x-2">
                  <button
                    v-if="index > 0"
                    @click="moveImage(index, 'up')"
                    class="p-2 bg-white rounded-full dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    ⬆️
                  </button>
                  <button
                    v-if="index < images.length - 1"
                    @click="moveImage(index, 'down')"
                    class="p-2 bg-white rounded-full dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    ⬇️
                  </button>
                  <button
                    @click="removeImage(index)"
                    class="p-2 bg-white rounded-full dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    ❌
                  </button>
                </div>
              </div>
              <div class="mt-2 text-sm text-gray-600 truncate dark:text-gray-400">
                {{ image.name }}
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-center space-x-4">
            <button
              @click="generatePDF"
              :disabled="isProcessing"
              class="px-6 py-2 text-white transition-colors bg-green-500 rounded-lg hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ isProcessing ? '正在生成...' : '生成PDF' }}
            </button>
            <button
              @click="clearImages"
              class="px-6 py-2 text-white transition-colors bg-red-500 rounded-lg hover:bg-red-600"
            >
              清空图片
            </button>
          </div>
        </div>

        <!-- 空状态 -->
        <div 
          v-else 
          class="p-8 text-center border-2 border-gray-300 border-dashed rounded-lg dark:border-gray-600"
        >
          <p class="text-gray-500 dark:text-gray-400">
            还没有选择任何图片，点击上方按钮添加图片
          </p>
        </div>
      </div>
    </div>
  </div>
</template> 